package cn.manyufun.myf.ui.main.activity;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.Toast;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.ArrayList;

import butterknife.BindView;
import cn.manyufun.myf.R;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.TabEntity;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.ui.main.fragment.CollectionFragment;
import cn.manyufun.myf.ui.main.fragment.ComicsFragment;
import cn.manyufun.myf.ui.main.fragment.NewsMainFragment;
import cn.manyufun.myf.ui.main.fragment.UserInfoFragment;
import rx.functions.Action1;

/**
 * @author Kevin Xiao
 * @date Create Date: 2017-12-26
 * @Description
 */
public class MainActivity extends BaseActivity {
    private static final int PERMISSION_CODE = 123;
    @BindView(R.id.tab_layout)
    CommonTabLayout tabLayout;

    private String[] mTitles = {"推荐", "漫画", "收藏", "我的"};
    private int[] mIconSelectIds = {
            R.drawable.ic_tab_home_active, R.drawable.ic_tab_comics_active, R.drawable.ic_tab_collection_active, R.drawable.ic_tab_profile_active
    };
    private int[] mIconUnselectIds = {
            R.drawable.ic_tab_home_normal, R.drawable.ic_tab_comics_normal, R.drawable.ic_tab_collection_normal, R.drawable.ic_tab_profile_normal
    };
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private ComicsFragment comicsFragment;
    private NewsMainFragment newsMainFragment;
    private CollectionFragment collectionFragment;
    private UserInfoFragment userInfoFragment;
    //    private ComicsFragment comicsFragment;
//    private CollectionFragment collectionFragment;
//    private UserInfoFragment userInfoFragment;
    private static int tabLayoutHeight;

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        initTab();
        initPermission();
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, PERMISSION_CODE);
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //切换daynight模式要立即变色的页面
//        ChangeModeController.getInstance().init(this,R.attr.class);
        super.onCreate(savedInstanceState);
        //初始化frament
        initFragment(savedInstanceState);
        tabLayout.measure(0, 0);
        tabLayoutHeight = tabLayout.getMeasuredHeight();
        //监听菜单显示或隐藏
        mRxManager.on(AppConstant.MENU_SHOW_HIDE, new Action1<Boolean>() {

            @Override
            public void call(Boolean hideOrShow) {
                startAnimation(hideOrShow);
            }
        });
    }

    /**
     * 初始化tab
     */
    private void initTab() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        tabLayout.setTabData(mTabEntities);
        //点击监听
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                SwitchTo(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    /**
     * 初始化碎片
     */
    private void initFragment(Bundle savedInstanceState) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        int currentTabPosition = 0;
        if (savedInstanceState != null) {
            comicsFragment = (ComicsFragment) getSupportFragmentManager().findFragmentByTag("comicsFragment");
            newsMainFragment = (NewsMainFragment) getSupportFragmentManager().findFragmentByTag("newsMainFragment");
            collectionFragment = (CollectionFragment) getSupportFragmentManager().findFragmentByTag("collectionFragment");
            userInfoFragment = (UserInfoFragment) getSupportFragmentManager().findFragmentByTag("userInfoFragment");
//            comicsFragment = (ComicsFragment) getSupportFragmentManager().findFragmentByTag("comicsFragment");
//            collectionFragment = (CollectionFragment) getSupportFragmentManager().findFragmentByTag("videoMainFragment");
//            userInfoFragment = (UserInfoFragment) getSupportFragmentManager().findFragmentByTag("careMainFragment");
            currentTabPosition = savedInstanceState.getInt(AppConstant.HOME_CURRENT_TAB_POSITION);
        } else {
            comicsFragment = new ComicsFragment();
            newsMainFragment = new NewsMainFragment();
            collectionFragment = new CollectionFragment();
            userInfoFragment = new UserInfoFragment();
//            comicsFragment = new ComicsFragment();
//            collectionFragment = new CollectionFragment();
//            userInfoFragment = new UserInfoFragment();

            transaction.add(R.id.fl_body, newsMainFragment, "newsMainFragment");
            transaction.add(R.id.fl_body, comicsFragment, "comicsFragment");
            transaction.add(R.id.fl_body, collectionFragment, "collectionFragment");
            transaction.add(R.id.fl_body, userInfoFragment, "userInfoFragment");
        }
        transaction.commit();
        SwitchTo(currentTabPosition);
        tabLayout.setCurrentTab(currentTabPosition);
    }

    /**
     * 切换
     */
    private void SwitchTo(int position) {
        LogUtils.logd("主页菜单position" + position);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (position) {
            //首页
            case 0:
                transaction.hide(userInfoFragment);
                transaction.hide(comicsFragment);
                transaction.hide(collectionFragment);
                transaction.show(newsMainFragment);
                transaction.commitAllowingStateLoss();
                break;
            //书影音
            case 1:
                transaction.hide(newsMainFragment);
                transaction.hide(userInfoFragment);
                transaction.hide(collectionFragment);
                transaction.show(comicsFragment);
                transaction.commitAllowingStateLoss();
                break;
            //广播
            case 2:
                transaction.hide(newsMainFragment);
                transaction.hide(comicsFragment);
                transaction.hide(userInfoFragment);
                transaction.show(collectionFragment);
                transaction.commitAllowingStateLoss();
                break;
            //我的
            case 3:
                transaction.hide(newsMainFragment);
                transaction.hide(comicsFragment);
                transaction.hide(collectionFragment);
                transaction.show(userInfoFragment);
                transaction.commitAllowingStateLoss();
                break;
            default:
                break;
        }
    }

    /**
     * 菜单显示隐藏动画
     *
     * @param showOrHide
     */
    private void startAnimation(boolean showOrHide) {
        final ViewGroup.LayoutParams layoutParams = tabLayout.getLayoutParams();
        ValueAnimator valueAnimator;
        ObjectAnimator alpha;
        if (!showOrHide) {
            valueAnimator = ValueAnimator.ofInt(tabLayoutHeight, 0);
            alpha = ObjectAnimator.ofFloat(tabLayout, "alpha", 1, 0);
        } else {
            valueAnimator = ValueAnimator.ofInt(0, tabLayoutHeight);
            alpha = ObjectAnimator.ofFloat(tabLayout, "alpha", 0, 1);
        }
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                layoutParams.height = (int) valueAnimator.getAnimatedValue();
                tabLayout.setLayoutParams(layoutParams);
            }
        });
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(500);
        animatorSet.playTogether(valueAnimator, alpha);
        animatorSet.start();
    }

    /**
     * 监听全屏视频时返回键
     */
    private long exitTime = 0;

    @Override
    public void onBackPressed() {
//        if (JCVideoPlayer.backPress()) {
//            return;
//        }
        super.onBackPressed();
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //奔溃前保存位置
//        LogUtils.loge("onSaveInstanceState进来了1");
        if (tabLayout != null) {
//            LogUtils.loge("onSaveInstanceState进来了2");
            outState.putInt(AppConstant.HOME_CURRENT_TAB_POSITION, tabLayout.getCurrentTab());
        }
    }
}
